import { defineStore } from 'pinia'

export interface ISysConfig {
  config: object
  routes: Array<object>
}
interface IState {
  cfg: ISysConfig[]
}

export const useConfigStore = defineStore({
  id: 'config',
  state: (): IState => ({
    cfg: JSON.parse(window.sessionStorage.getItem('syscfg') as string) || {
      config: {},
      routes: []
    }
  }),
  // getters: {
  //   getConfig: (state) => {return state.cfg.config},
  //   getRoutes: (state) => state.cfg.routes
  // },
  actions: {
    setStorage() {
      window.sessionStorage.setItem('syscfg', JSON.stringify(this.cfg))
    },
    setConfig(cfgs: object | {}) {
      if (cfgs) {
        this.cfg.config = cfgs
      } else {
        this.cfg.config = null
      }
      this.setStorage()
    },
    setRoutes(route: Array<object> | []) {
      if (route) {
        route.forEach((r) => {
          delete r.id
          delete r.parentId
          delete r.weight
          if (r.hasOwnProperty('children')) {
            delete r.componentPath
          }
        })
        this.cfg.routes = route
      } else {
        this.cfg.routes = null
      }
      this.setStorage()
    }
  }
})
